//
//  AddRepairItemSubView.m
//  HondaPro_2
//
//  Created by Eric on 13-6-28.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "AddRepairItemSubView.h"
#import "mm_addRepairItemToIndicationListUserDefinedCell.h"
#import "MyAFNetWorkManager.h"
#import "SVProgressHUD.h"
#import "MJRefresh.h"

@interface AddRepairItemSubView ()

/** 收费区分列表 */
@property(nonatomic,strong)NSMutableDictionary *chargeDiff;
@property(nonatomic,strong)NSMutableArray *chargeDiffKeys;

/** 维修车型组数据列表 */
@property(nonatomic,strong)NSMutableArray *arrDisDataForCarType;
@property(nonatomic,strong)NSMutableDictionary *carTypeDic;
/** 选中行索引 */
@property(nonatomic,assign)int selectedRowIndex;

/** 维修分类 */
@property(nonatomic,strong)NSMutableArray *repairTypeNames;
@property(nonatomic,strong)NSMutableDictionary *repairTypeDic;
@property(nonatomic,weak)UIButton *repairTypeBtn;

/** 工时单价 */
@property(nonatomic,strong)NSMutableArray *labourPrices;
@property(nonatomic,weak)UIButton *labourPriceBtn;

@end

@implementation AddRepairItemSubView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self repairTypeNames];
        [self createControls];
        self.selectedRowIndex = -1;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChange:) name:UITextFieldTextDidChangeNotification object:nil];
    }
    return self;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}

#pragma mark - 创建控件

-(void)createControls
{
    //创建label
    
    [self setupLabelWithTitle:@"车 型:" frame:CGRectMake(0, 0, 100, 30)];
    
    [self setupLabelWithTitle:@"维修项目代码:" frame:CGRectMake(270, 0, 150, 30)];
    
    [self setupLabelWithTitle:@"维修项目名称:" frame:CGRectMake(0, 38, 150, 30)];
    
    [self setupLabelWithTitle:@"标准工时：" frame:CGRectMake(0, 340, 80, 30)];
    
    [self setupLabelWithTitle:@"工时单价：" frame:CGRectMake(0, 390, 80, 30)];
    
    [self setupLabelWithTitle:@"工时费：" frame:CGRectMake(0, 440, 80, 30)];
    
    [self setupLabelWithTitle:@"维修分类：" frame:CGRectMake(210, 390, 80, 30)];
    
    [self setupLabelWithTitle:@"费用区分：" frame:CGRectMake(210, 440, 80, 30)];
    
    //创建text
    repairIdTxt = [self setupTextFieldWithFrame:CGRectMake(400, 0, 200, 30)];//177, 38, 150, 34

    repairNameTxt = [self setupTextFieldWithFrame:CGRectMake(130, 40, 350, 30)];
    
    standardWorkHourTxt = [self setupTextFieldWithFrame:CGRectMake(80, 340, 120, 30)];
    
    [self setupDropdownBackgroud:CGRectMake(80, 390, 120, 34)];
    self.labourPriceBtn = [self setupDropdownButtonWithFrame:CGRectMake(79, 387, 122, 40) method:@selector(dropdownTapped:)];
//    workHourPriceTxt = [self setupTextFieldWithFrame:CGRectMake(80, 390, 120, 30)];

    workHourChargeTxt = [self setupTextFieldWithFrame:CGRectMake(80, 440, 120, 30)];
    workHourChargeTxt.enabled = NO;
    workHourChargeTxt.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1];
    
    //初始化控件的内容
    standardWorkHourTxt.text = @"0";
    workHourPriceTxt.text = @"0";
    workHourChargeTxt.text = @"0";
    
    standardWorkHourTxt.delegate = self;
    workHourPriceTxt.delegate = self;
    
    [self setupDropdownBackgroud:CGRectMake(290, 390, 150, 34)];
    
    self.repairTypeBtn = [self setupDropdownButtonWithFrame:CGRectMake(289, 387, 152, 40) method:@selector(dropdownTapped:)];
    
    [self setupDropdownBackgroud:CGRectMake(290, 440, 150, 34)];
    
    charDiffBtn = [self setupDropdownButtonWithFrame:CGRectMake(289, 437, 152, 40) method:@selector(dropdownTapped:)];
    
    //创建button
    [self setupButtonWithTitle:@"查询" frame:CGRectMake(844, 0, 80, 30) method:@selector(searchBtnPressed:)];
    
    [self setupButtonWithTitle:@"清空" frame:CGRectMake(844, 40, 80, 30) method:@selector(clearBtnPressed:)];
    
    [self setupButtonWithTitle:@"确定新增" frame:CGRectMake(774, 340, 120, 40) method:@selector(addNewBtnClicked)];
    
    [self setupDropdownBackgroud:CGRectMake(101, 2, 150, 30)];
    
    repairGroupBtn =[[UILabel alloc]initWithFrame:CGRectMake(100, 0, 152, 34)];
    repairGroupBtn.backgroundColor=[UIColor whiteColor];
    [self addSubview:repairGroupBtn];
    
    
    //创建tableView
    [self createTableViewDis];
}
-(void)setCarType:(NSString *)carType
{
    _carType=carType;
    repairGroupBtn.text=carType;
}

-(void)setJobSheetLabourPrice:(NSString *)jobSheetLabourPrice{
    _jobSheetLabourPrice = jobSheetLabourPrice;
    [self.labourPriceBtn setTitle:jobSheetLabourPrice forState:UIControlStateNormal];
}

-(void)setupLabelWithTitle:(NSString *)title frame:(CGRect)frame{
    UILabel *repairIdLbl = [[UILabel alloc] initWithFrame:frame];
    repairIdLbl.textColor = [UIColor grayColor];
    repairIdLbl.font = [UIFont fontWithName:@"ArialMT" size:16];
    repairIdLbl.text = title;
    repairIdLbl.textAlignment=NSTextAlignmentCenter;
    [self addSubview:repairIdLbl];
}

-(UITextField *)setupTextFieldWithFrame:(CGRect)frame{
    UITextField *txt = [[UITextField alloc] initWithFrame:frame];
    txt.borderStyle = UITextBorderStyleLine;
    txt.textColor = [UIColor grayColor];
    txt.font = [UIFont fontWithName:@"ArialMT" size:16];
    [self addSubview:txt];
    return txt;
}

-(void)setupButtonWithTitle:(NSString *)title frame:(CGRect)frame method:(SEL)method{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    [btn setBackgroundImage:[UIImage imageNamed:@"mm_red_btn.png"] forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    btn.titleLabel.font = [UIFont fontWithName:@"ArialMT" size:16];
    [btn addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn];
}

-(UIButton *)setupDropdownButtonWithFrame:(CGRect)frame method:(SEL)method{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    btn.backgroundColor = [UIColor clearColor];
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn setBackgroundImage:[UIImage imageNamed:@"10.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn];
    return btn;
}

-(void)setupDropdownBackgroud:(CGRect)frame{
    UIView * bg = [[UIView alloc] initWithFrame:frame];
    bg.backgroundColor = [UIColor grayColor];
    [self addSubview:bg];
}

-(void)createTableViewDis
{
    //创建label
    UIView *bottomLbl = [[UIView alloc] initWithFrame:CGRectMake(0, 80, self.frame.size.width, 50)];
    bottomLbl.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    [self addSubview:bottomLbl];
    
    CGFloat w =bottomLbl.mj_w/3;
    [self setupLabelWithTitle:@"维修项目代码" frame:CGRectMake(0, 80, w, 50)];
    
    [self setupLabelWithTitle:@"维修项目名称" frame:CGRectMake(w, 80, w, 50)];
    
//    [self setupLabelWithTitle:@"维修分类" frame:CGRectMake(2*w, 80, w, 50)];
//
    [self setupLabelWithTitle:@"标准工时" frame:CGRectMake(2*w, 80, w, 50)];
    
//    [self setupLabelWithTitle:@"索赔工时" frame:CGRectMake(818, 80, 106, 50)];
    
    _arrRepairItemListToDisplay = [NSMutableArray arrayWithCapacity:5];
    
    tableViewDis = [[UITableView alloc] initWithFrame:CGRectMake(0, 130, self.frame.size.width, 200)];
    tableViewDis.delegate = self;
    tableViewDis.dataSource = self;
    tableViewDis.backgroundColor = [UIColor clearColor];
    
    [self addSubview:tableViewDis];
    
    __unsafe_unretained UITableView *tableView = tableViewDis;
    
    // 下拉刷新
//    tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        
//        
//        [tableView.mj_header endRefreshing];
//    }];
    
    
    // 上拉刷新
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self footerRefresh];
        
        [tableView.mj_footer endRefreshing];
    }];
}

- (void)footerRefresh
{
    [self endEditing:YES];
    
    self.selectedRowIndex = -1;
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:3];
    
    NSString *group = repairGroupBtn.text;
    NSString *groupCode = repairIdTxt.text;
    NSString *groupName = repairNameTxt.text;
    if (group.length>0) {
        [param setObject:self.carTypeDic[group] forKey:@"MODEL_LABOUR_CODE"];
    }
    if (groupCode.length>0) {
        [param setObject:groupCode forKey:@"LABOUR_CODE"];
    }
    if (groupName.length>0) {
        [param setObject:[groupName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"LABOUR_NAME"];
    }
    
    [param setObject:[NSString stringWithFormat:@"%d",_arrRepairItemListToDisplay.count] forKey:@"FROM"];
    [param setObject:[NSString stringWithFormat:@"%d",_arrRepairItemListToDisplay.count+10] forKey:@"TO"];
    
    [SVProgressHUD showWithStatus:@"请等待...."];
    [MyAFNetWorkManager postWithParam:param andAction:@"CHOOSE_REPAIR_ITEM_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        
        [SVProgressHUD dismiss];
        
        if (!error) {
            [_arrRepairItemListToDisplay addObjectsFromArray:obj[@"TM_REPAIR_ITEM"]];
            
            //刷新表单
            [tableViewDis reloadData];
        }else{
            NSLog(@"%@",error);
        }
        
    }];
}

#pragma mark - tableView dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    /*
     此处的操作是：
     返回维修列表的count，即有多少项需要显示
     */
    
    return [_arrRepairItemListToDisplay count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    mm_addRepairItemToIndicationListUserDefinedCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (nil == cell)
    {
        cell = [[mm_addRepairItemToIndicationListUserDefinedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    //cell的风格是：浅浅灰色和浅灰色间隔出现，第一行是浅灰色
    NSInteger row = [indexPath row];
    switch (row%2)
    {
        case 0:
            //浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
            break;
        case 1:
            //浅浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
            break;
            
        default:
            break;
    }
    
    //给cell上赋值
    if (row < [_arrRepairItemListToDisplay count])
    {
        for (int i = 0; i<[cell.arrAllKeysOnCell count]; i++)
        {
            NSString *strKey = cell.arrAllKeysOnCell[i];
            NSDictionary *dic = _arrRepairItemListToDisplay[row];
            NSString *text = nil;
            if ([strKey isEqualToString:@"STD_LABOUR_HOUR"]||[strKey isEqualToString:@"CLAIM_LABOUR"]||[strKey isEqualToString:@"PART_QUANTITY"]) {
                text = [dic[strKey]stringValue];
            }else{
                text = dic[strKey];
            }
            
            if ([strKey isEqualToString:@"REPAIR_TYPE_CODE"]) {
                text = [self getNameWithCode:dic[@"REPAIR_TYPE_CODE"]];
            }
            ((UILabel *)[cell.dicAllLblsOnCell objectForKey:strKey]).text = text;
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    else
    {
        for (int i = 0; i<[cell.arrAllKeysOnCell count]; i++)
        {
            NSString *strKey = [cell.arrAllKeysOnCell objectAtIndex:i];
            ((UILabel *)[cell.dicAllLblsOnCell objectForKey:strKey]).text = @"";
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return cell;
}

- (NSString *)getNameWithCode:(NSString *)code
{
    NSString *str = nil;
    NSArray *arr = [self readershuDICimform][@"TM_REPAIR_TYPE_ITEM"];
    for (NSDictionary *dic in arr) {
        if ([dic[@"CODE"] isEqualToString:code]) {
            str = dic[@"NAME"];
        }
    }
    
    return str;
}

#pragma mark - tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    
    if (row<[_arrRepairItemListToDisplay count])
    {
        
        NSDictionary *dicRepairItemBySearchTmp = _arrRepairItemListToDisplay[row];
        //工时费 = 标准工时 * 工时单价
        double stdHour = [dicRepairItemBySearchTmp[@"STD_LABOUR_HOUR"]doubleValue];
        standardWorkHourTxt.text = [NSString stringWithFormat:@"%.2f",stdHour];
        [self computeAmout];
        self.selectedRowIndex = row;
    }
    else
    {
        return;
    }
}


#pragma mark - 回调方法

-(void)searchBtnPressed:(UIButton *)sender
{
    [self endEditing:YES];
    
    self.selectedRowIndex = -1;
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:3];
    
    NSString *group = repairGroupBtn.text;
    NSString *groupCode = repairIdTxt.text;
    NSString *groupName = repairNameTxt.text;
    if (group.length>0) {
        [param setObject:self.carTypeCode forKey:@"MODEL_LABOUR_CODE"];
    }
    if (groupCode.length>0) {
        [param setObject:groupCode forKey:@"LABOUR_CODE"];
    }
    if (groupName.length>0) {
        [param setObject:[groupName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"LABOUR_NAME"];
    }
    
    [param setObject:@"1" forKey:@"FROM"];
    [param setObject:@"10" forKey:@"TO"];
    
    [SVProgressHUD showWithStatus:@"请等待...."];
    [MyAFNetWorkManager postWithParam:param andAction:@"CHOOSE_REPAIR_ITEM_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        
        [SVProgressHUD dismiss];
        
        if (!error) {
            [_arrRepairItemListToDisplay setArray:obj[@"TM_REPAIR_ITEM"]];
            
            //刷新表单
            [tableViewDis reloadData];
        }else{
            NSLog(@"%@",error);
        }
        
    }];
    
}

-(void)clearBtnPressed:(UIButton *)sender
{
//    [repairGroupBtn setTitle:nil forState:UIControlStateNormal];
    repairIdTxt.text = @"";
    repairNameTxt.text = @"";
}


//判断项目号是否有重复的
-(BOOL)repairItemNotRepeat
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSArray *arrTmp = [[[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"] objectAtIndex:modelIns.nRowForIndicationList] objectForKey:@"repairItemList"];
    
    for (int i = 0; i<[arrTmp count]; i++)
    {
        NSString *str = [[arrTmp objectAtIndex:i] objectForKey:@"repairId"];
        if ([str isEqualToString:repairIdTxt.text])
        {
            return NO;
        }
    }
    return YES;
}


-(void)dropdownTapped:(UIButton *)sender
{
    //创建下拉菜单
    [self createThePopViewControl:sender];
    NSArray *source = nil;
    if (sender == self.labourPriceBtn) {
        source = self.labourPrices;
    }else if (sender == self.repairTypeBtn){
        source = self.repairTypeNames;
    }else if (sender == charDiffBtn){
        source = self.chargeDiffKeys;
    }
    else if (sender == repairGroupBtn){
        source = self.arrDisDataForCarType;
    }
    contentCon.list = source;
    [contentCon.myTableView reloadData];
}

/*just for test*/
-(void)jsonParseFromJsonFileFRTList
{
    NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"JsonFileForFRTList" ofType:@"json"];
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[HelpClass jsonParseByJsonFileStr:jsonFilePath]];
    
    NSLog(@"dic = %@",dic);
    
    //dic是从json file中解析出来的数据，更新该类中的属性
    _arrFRTList = [dic objectForKey:MM_FRT_LIST_KEY_STR_];
}

-(void)jsonParseFromJsonFileRepairItemListBasedOnFRTList
{
    NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"JsonFileForRepairItemListBasedOnFRTList" ofType:@"json"];
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[HelpClass jsonParseByJsonFileStr:jsonFilePath]];
    
    NSLog(@"dic = %@",dic);
    
    _arrRepairItemListBasedOnFRT = [dic objectForKey:MM_REPAIR_ITEM_LIST_KEY_STR_];
}
/*just for test*/

//判断作业指示的 服务类型 是否是保修
-(BOOL)isWarrantyByServiceInIndication
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSString *str = [[[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"] objectAtIndex:modelIns.nRowForIndicationList] objectForKey:@"serviceType"];
    NSRange range = [[self getNameByServiceId:str] rangeOfString:@"保修"];
    if (range.length == [@"保修" length])
    {
        return YES;
    }
    return NO;
}


//创建下拉菜单方法
-(void)createThePopViewControl:(UIButton *)sender
{
    if (!contentCon)
    {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
        contentCon.delegate = self;
    }
    
    contentCon.btnSender=sender;
    
    popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [popCon setPopoverContentSize:CGSizeMake(sender.frame.size.width, 280)];
    
    [popCon presentPopoverFromRect:CGRectMake(40, 15, 70, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

//弹出的回调方法
-(void)selectDelegate:(NSInteger)row btn:(UIButton *)btn
{
    NSString *key = nil;
    if (btn == repairGroupBtn){
    
        key = self.arrDisDataForCarType[row];
    }else if (btn == charDiffBtn){
        key = self.chargeDiffKeys[row];
        [self labourPriceBtnControl:key];//选择收费区分的控制逻辑
    }else if (btn == self.repairTypeBtn){
        key = self.repairTypeNames[row];
    }else if (btn == self.labourPriceBtn){
        key = self.labourPrices[row];
    }
    
    [btn setTitle:key forState:UIControlStateNormal];
    
    if (btn == self.labourPriceBtn||btn == charDiffBtn){
        [self computeAmout];
    }
    
    //清空数据，退出控件
    [popCon dismissPopoverAnimated:YES];
    popCon = nil;
}

/** 选择收费区分的控制逻辑 */
-(void)labourPriceBtnControl:(NSString *)name{
    //如果收费区分是首保、保修、市场活动、PDI、配件索赔，则工时单价不可修改，工时单价取车辆信息的工时单价
    NSString *code = self.chargeDiff[name];
    if ([code isEqualToString:@"S002"]||[code isEqualToString:@"S004"]||[code isEqualToString:@"S008"]||[code isEqualToString:@"S009"]||[code isEqualToString:@"S010"]) {
        [self.labourPriceBtn setTitle:self.labourPrice forState:UIControlStateNormal];
        self.labourPriceBtn.enabled = NO;
    }else{
        
        if (!self.labourPriceBtn.enabled) {
            self.labourPriceBtn.enabled = YES;
            [self.labourPriceBtn setTitle:self.jobSheetLabourPrice forState:UIControlStateNormal];
        }
        
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    textField.keyboardType = UIKeyboardTypeNumberPad;
    
//    int offset = 350;//键盘高度350
//    NSTimeInterval animationDuration = 0.30f;
//    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
//    [UIView setAnimationDuration:animationDuration];
//    float width = self.view.frame.size.width;
//    float height = self.view.frame.size.height;
//    if(offset > 0)
//    {
//        CGRect rect = CGRectMake(0.0f, -offset,width,height);
//        self.view.frame = rect;
//    }
//    [UIView commitAnimations];
    
    //将scrollView上托到最大位置
    [[NSNotificationCenter defaultCenter] postNotificationName:@"mm_addAndModifyViewControllerScrollViewScroll" object:nil];
}


-(void)textFieldValueChange:(NSNotification *)note{
    [self computeAmout];
}

-(void)computeAmout{
    double stdHour = [standardWorkHourTxt.text doubleValue];
    double price = [self.labourPriceBtn.currentTitle doubleValue];
    workHourChargeTxt.text = [NSString stringWithFormat:@"%.2f",stdHour * price];
}

//得到列表中的最大序号
-(NSInteger)getTheMaxNumber
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSArray *arrTmp = [[[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"] objectAtIndex:modelIns.nRowForIndicationList] objectForKey:@"repairItemList"];
    
    NSInteger nMaxNumber = 0;
    
    for (int i = 0; i<[arrTmp count]; i++)
    {
        NSString *strTmp = [[arrTmp objectAtIndex:i] objectForKey:MM_REPAIR_NUMBER_KEY_STR_];
        nMaxNumber = nMaxNumber < [strTmp integerValue] ? [strTmp integerValue] : nMaxNumber;
    }
    
    return nMaxNumber;
}

//-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
////    NSCharacterSet *cs;
////    cs = [[NSCharacterSet characterSetWithCharactersInString:@".0123456789\n"]invertedSet];
////    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
////    BOOL canChange = [string isEqualToString:filtered];
//    
//    return true;
//}

//根据ID取名字
-(NSString *)getNameByServiceId:(NSString *)serviceId
{
    for (int i = 0; i<[self.arrOriginalDataForServiceType count]; i++)
    {
        NSString *strId = [[self.arrOriginalDataForServiceType objectAtIndex:i] objectForKey:@"serviceTypeId"];
        NSString *strName = [[self.arrOriginalDataForServiceType objectAtIndex:i] objectForKey:@"serviceTypeName"];
        if ([serviceId isEqualToString:strId])
        {
            return strName;
        }
    }
    return @"";
}

/** 确定新增 */
-(void)addNewBtnClicked{
    NSString *msg = [self getErrorMsg];
    if (msg) {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        return;
    }
    NSMutableDictionary *seletedData = _arrRepairItemListToDisplay[self.selectedRowIndex];
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
//    ;
    NSArray * repairArr = modelIns.repairProjects;
    for (NSDictionary * repairDic in repairArr) {
        if ([repairDic[@"LABOUR_CODE"] isEqualToString:seletedData[@"LABOUR_CODE"]]) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil message:@"该维修项目已存在，不可重复添加！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
    }
    NSString *chargeDiffVal = self.chargeDiff[charDiffBtn.titleLabel.text];
    NSString *repairTypeCode = self.repairTypeDic[self.repairTypeBtn.titleLabel.text];
    NSNumber *stdHour = [NSNumber numberWithDouble:[standardWorkHourTxt.text doubleValue]];
    if (!chargeDiffVal) {
        chargeDiffVal = @"";
    }
    [seletedData setObject:@"" forKey:@"ITEM_ID"];//id
    [seletedData setObject:@"A" forKey:@"STATUS"];//状态
    [seletedData setObject:@(self.discount) forKey:@"DISCOUNT"];//折扣
    [seletedData setObject:chargeDiffVal forKey:@"CHARGE_PARTITION_CODE"];//收费区分
    seletedData[@"REPAIR_TYPE_CODE"] = repairTypeCode;//维修分类
    [seletedData setObject:stdHour forKey:@"STD_LABOUR_HOUR"];//标准工时
    [seletedData setObject:self.labourPriceBtn.currentTitle forKey:@"LABOUR_PRICE"];//工时单价
    [seletedData setObject:workHourChargeTxt.text forKey:@"LABOUR_AMOUNT"];//工时费
    [modelIns.repairProjects addObject:seletedData];
    //更新完数据后刷新界面
    [[NSNotificationCenter defaultCenter] postNotificationName:SECOND_REPAIR_ITEM_LIST_MSG_ object:nil];
    [SVProgressHUD showInfoWithStatus:@"新增成功"];
}

-(NSString *)getErrorMsg{
    NSString *msg = nil;
    if (self.selectedRowIndex == -1) {
        msg = @"请选择一行数据！";
    }else if (self.repairTypeBtn.titleLabel.text.length<=0){
        msg = @"请选择维修分类";
    }else if (charDiffBtn.titleLabel.text.length<=0){
        msg = @"请选择收费区分";
    }else if (self.labourPriceBtn.currentTitle.length<=0){
        msg = @"请选择工时单价";
    }
    return msg;
}

#pragma mark -懒加载
/** 收费区分 */
-(NSMutableArray *)chargeDiffKeys{
    if (_chargeDiffKeys == nil) {
        _chargeDiffKeys= [NSMutableArray array];
        _chargeDiff = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_CHARGE_PARTITION"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            if ([name isEqualToString:@"自费"]||[name isEqualToString:@"免费"]||[name isEqualToString:@"保险"]||[name isEqualToString:@"店端活动"]||[name isEqualToString:@"客户活动"]) {
                [_chargeDiffKeys addObject:name];
                [_chargeDiff setObject:val forKey:name];
            }
            
        }
    }
    return _chargeDiffKeys;
}

/** 维修车型组 */
-(NSMutableArray *)arrDisDataForCarType{
    if (_arrDisDataForCarType == nil) {
        _arrDisDataForCarType= [NSMutableArray array];
        _carTypeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_MODEL_LABOUR"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            if (name&&val) {
                [_arrDisDataForCarType addObject:name];
                [_carTypeDic setObject:val forKey:name];
            }
        }
    }
    return _arrDisDataForCarType;
}

-(NSMutableArray *)repairTypeNames{
    if (_repairTypeNames == nil) {
        _repairTypeNames= [NSMutableArray array];
        _repairTypeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_REPAIR_TYPE_ITEM"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_repairTypeNames addObject:name];
            [_repairTypeDic setObject:val forKey:name];
        }
    }
    return _repairTypeNames;
}

/** 工时单价 */
-(NSMutableArray *)labourPrices{
    if (_labourPrices == nil) {
        _labourPrices= [NSMutableArray array];
        NSMutableArray *arr = [self readershuDICimform][@"TM_LABOUR_PRICE"];
        for (NSDictionary *dic in arr) {
            NSString *name = [dic[@"NAME"]stringValue];
//            NSString *val = dic[@"CODE"];
            [_labourPrices addObject:name];
        }
    }
    return _labourPrices;
}

-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    //nslog(@"%@",dic);
    return dic;
}

@end
